<?php


namespace app\api\controller\user;
/**
 * @title 小程序登录
 */

use app\api\controller\Common;
use app\api\model\UserModel;
use app\logic\ext\WxBizDataCrypt;
use app\logic\model\WxappModel;
use app\logic\ext\HttpRequest;
use think\App;
use app\logic\traits\Wx;
use think\facade\Cache;
class Login extends Common
{
    protected $appid;
    protected $appsecret;
    protected $needLogin=['getMobile'];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->app->bind('http',HttpRequest::class);
        $config = WxappModel::find(1)->toArray();
        $this->appid = $config['appid'];
        $this->appsecret = $config['appsecret'];
    }
    /**
     * @title 获取token,openid，session_key
     * @description 小程序授权接口
     * @method get/post
     * @param string code 12312312 小程序授权时的code 必填
     * @return string openid 1 用户openid
     * @return string session_key 1 session_key
     * @return string token 1 客户端与服务端交互标识
     * @return string pid 1 分享人的Id 
     * @return string login - [true 代表当前已经在另一个端绑定了。这个端就不需要再进行绑定]
     */
    public function login(){

        $code = $this->request->param('code');
        if(!$code){
            show_json("wxapp.login.not_find_code");
        }
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        // dd($appid,$appsecret,$code);
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
        $content=$this->app->http->curl_get($url);
        $content = json_decode($content,1);
        if(!isset($content['errcode']) || $content['errcode'] == 0){
            $openid = $content['openid'];
            $session_key = $content['session_key'];
            $unionid=$content['unionid'];
            //1.检测当前用户是否在第三方平台登陆
            $token = $this->CreateToken($openid);
            $user=(new UserModel())->findUser($_where=["unionid"=>$unionid],"*");
            if($user){
            	(new UserModel())->updateInfo(['openid'=>$openid],['id'=>$user['id']]);
            	$dxr =[
            		'openid'=>$openid,
            		'unionid'=>$unionid,
            		'session_key' => $session_key,
            		'login'=>true,
	                'token' => $token
	            ];
            }else{ 
	            $dxr =[
	            	'login'=>false,
	            	'unionid'=>$unionid,
	                'openid' => $openid,
	                'session_key' => $session_key,
	                'token' => $token
	            ];
            }
            show_json('code_common.success',$dxr);
        }else{
            show_json('code_common.error',$content['errmsg'],true);
        }
    }
    /**
     * @title 保存用户信息
     * @method get/post
     * @param string iv 123456789 授权信息时的iv 是
     * @param string openid 123456789 用户openid 是
     * @param string unionid 12452 用户unionid 是
     * @param string encryptedData 123456789 授权时获取的encryptedData(需要encode编码) 是
     * @param string session_key 123456789 session_key 是
     * @param string agent_id 123456789 上级id 否(分享过来用)
     */
    public function save(){
        global $user;
        $iv = $this->request->param('iv');
        $encryptedData = urldecode($this->request->param('encryptedData'));
        $session_key = $this->request->param('session_key');
        $agent_id = $this->request->param('agent_id','');
        $openid=$this->request->param('openid');
        $unionid=$this->request->param('unionid');
        $wx = new WxBizDataCrypt($this->appid,$session_key);
        $errCode=$wx->decryptData($encryptedData,$iv,$data);
        if($errCode == 0){
            $data = json_decode($data,true);
            /*if($agent_id == $this->request->param('agent_id')){
                $agent_id = null;
            }*/
            $user=(new UserModel())->getFindByOpenid($openid);
            $dxr = [
                'avatar' =>  $data['avatarUrl'],
                'sex' => $data['gender'],
                'nickname' => $data['nickName'],
                'is_collectors'=>1,
            ];
            if(!empty($user)){
                $bool= $user->save($dxr);
                show_json('code_common.success');
            }else{
                $dxr['nft']=(new UserModel())->createNft();;
                $dxr['agentid']=$agent_id;
                $dxr['openid']=$openid;
                $dxr['unionid']=$unionid;
                $bool= (new UserModel())->save($dxr);
            }
            if($bool){
                show_json('code_common.success');
            }else{
                show_json('code_common.error');
            }
        }else{
            show_json('code_common.error',"小程序码：".$errCode,true);
        }
    }

    /**
     * @title 保存用户手机号
     * @description 保存用户信息手机号
     * @method get/post
     * @param string iv 授权信息时的iv 是
     * @param string unionid 用户unionid 是
     * @param string encryptedData 授权时获取的encryptedData(需要encode编码) 是
     * @param string session_key session_key 是
     * @return int code 状态码
     * @return string msg 返回信息
     * @remark 备注
     * @number 99
     */
    public function getMobile(){
        global $user;
        $encryptedData = urldecode($this->request->param('encryptedData'));
        $iv = $this->request->param('iv');
        $sessionKey = $this->request->param('session_key');
        $wx = new WxBizDataCrypt($this->appid,$sessionKey);
        $errCode=$wx->decryptData($encryptedData,$iv,$data);
        $_unionid=$this->request->param('unionid');
        if($errCode == 0){
            $data = json_decode($data,1);
            $mobile = $data['phoneNumber'];
            if(isset($_unionid) && !empty($_unionid)){
	            $_data=(new UserModel())->findUser(['unionid'=>$this->request->param('unionid')],"*");
	            if($_data && $_data['mobile']!='' && $_data['mobile']!=$mobile){
	            	show_json('code_common.error',"当前小程序已绑定的手机号为:".$_data['mobile']."不需要再进行绑定",true);
	            	return false;
	            }
            }
            $user = (new UserModel())->find($user['id']);
            $user->mobile = intval($mobile);
            $user->save();
            $_key=md5('getUser'.$user['id']);
            Cache::del($_key);
            show_json('code_common.success');
        }else{
            show_json('code_common.error',"小程序码：".$errCode,true);
        }
    }
    function ceshiLogin(){
        $openid='oVWXj4gi7xeWLjbvVWetsopkLLjo';
        $token=$this->CreateToken($openid);
        $dxr =[
            'openid' => $openid,
            'token' => $token
        ];
        show_json('code_common.success',$dxr);
    }
}